import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import { loginApi, uerInfoApi, logoutApi } from '@/api/user';

interface UserInfo {
  userId: number;
  username: string;
  nickname: string;
  avatar: string;
  roles: string[];
  perms: string[];
}

interface AuthState {
  token: string | null;
  userInfo: UserInfo | null;
  isAuthenticated: boolean;
}

export const useAuth = () => {
  const [authState, setAuthState] = useState<AuthState>(() => ({
    token: localStorage.getItem('token'),
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
    isAuthenticated: !!localStorage.getItem('token')
  }));

  const setToken = useCallback((token: string | null) => {
    setAuthState((prev) => ({ ...prev, token, isAuthenticated: !!token }));
    if (token) {
      localStorage.setItem('token', token);
    } else {
      localStorage.removeItem('token');
    }
  }, []);

  const setUserInfo = useCallback((userInfo: UserInfo | null) => {
    setAuthState((prev) => ({ ...prev, userInfo }));
    if (userInfo) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    } else {
      localStorage.removeItem('userInfo');
    }
  }, []);

  const fetchUserInfo = useCallback(async () => {
    try {
      const { code, data } = await uerInfoApi();
      if (code === 200) {
        setUserInfo(data as UserInfo);
      } else {
        console.error('获取用户信息失败:', data);
        message.error('获取用户信息失败');
      }
    } catch (error) {
      console.error('获取用户信息出错:', error);
      message.error('获取用户信息时发生错误');
    }
  }, [setUserInfo]);

  const login = useCallback(
    async (username: string, password: string) => {
      try {
        const { code, data } = await loginApi({ username, password });
        if (code === 200) {
          fetchUserInfo();
          const { token, expires } = data as { token: string; expires: number };
          setToken(token);
          localStorage.setItem('token', (Date.now() + expires * 1000).toString());
        }
      } catch (error) {
        message.error('登录失败，请重试');
        console.error('登录错误:', error);
      }
    },
    [setToken, fetchUserInfo]
  );

  const logout = useCallback(async () => {
    try {
      await logoutApi();
      setToken(null);
      setUserInfo(null);
      message.success('已成功退出登录');
    } catch (error) {
      console.error('退出登录错误:', error);
      message.error('退出登录失败，请重试');
    }
  }, [setToken, setUserInfo]);

  useEffect(() => {
    const checkTokenExpiration = () => {
      const expirationTime = localStorage.getItem('token');
      if (expirationTime && Date.now() > parseInt(expirationTime, 10)) {
        logout();
        message.warning('登录已过期，请重新登录');
      }
    };

    const interval = setInterval(checkTokenExpiration, 60000); // 每分钟检查一次
    return () => clearInterval(interval);
  }, [logout]);

  return {
    token: authState.token,
    userInfo: authState.userInfo,
    isAuthenticated: authState.isAuthenticated,
    login,
    logout
  };
};
